import React, {useState} from 'react';
import {Upload, message, Row, Col, Space, Button, Typography, Tabs} from 'antd';
import {base_url} from "../../../utils/requset";
import {InboxOutlined} from "@ant-design/icons";
import "@icon-park/react/styles/index.css"
import {
    Analysis,
    History,
} from '@icon-park/react';

import backgroundImage from "../../../images/form_bg@2x.2d429e6ecd7d2c432e6f.png";
import DataReport from "./DataReport";
import UploadRecord from "./UploadRecord";
import { useSelector } from "react-redux";
import {request} from "../../../utils/requset";

const {Dragger} = Upload;
const {Title} = Typography;

const backgroundStyle = {
    backgroundImage: `url(${backgroundImage})`,
    backgroundSize: 'cover', // 使背景图片覆盖整个容器
    backgroundPosition: 'center', // 背景图片居中
    backgroundRepeat: 'no-repeat', // 防止背景图片重复
    // minHeight: '100vh', // 确保背景图片覆盖整个视口高度
    // 其他您需要的样式
};


function FileUpload() {
    const props = {
        name: 'file',
        multiple: true,
        directory: false,  // 禁止选择文件夹
        accept: '.xlsx,.xlsm',
        action: base_url+'/file_upload/upload',
        onChange(info) {
            const {status, response} = info.file;
            if (status !== 'uploading') {
                // console.log(info.file, info.fileList);
            }
            if (status === 'done') {
                message.success(`文件 ${info.file.name} 上传成功`);
                // console.log(response);
                setRefreshFlag(!refreshFlag);
            } else if (status === 'error') {
                if (response && response.error) {
                    message.error(`文件 ${info.file.name} 上传失败，参考错误信息：${response.error}`);
                } else if (response) {
                    message.error(`文件 ${info.file.name} 上传失败，参考错误信息：${JSON.stringify(response)}`);

                }
            }
        },
        onDrop(e){
            // 获取拖拽的文件或文件夹
            const items = e.dataTransfer.items;
            // console.log("items",items)
            for (let i = 0; i < items.length; i++) {
              const item = items[i];
              // console.log("item",item)
              // console.log("kind",item.kind)
              // console.log("type",item.type)

              // 如果是文件夹，阻止上传
              if (
                    (item.kind === 'folder' || item.type === ""||
                    item.type !== "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
                    && item.type !== "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.macroEnabled.12"
                    && item.type !== "application/vnd.ms-excel.sheet.macroEnabled.12"
              ) {
                message.error('不支持的文件格式或文件夹');
                e.preventDefault();  // 阻止文件夹的拖拽行为
                return;
              }
            }
        },
        // 尝试修改上传文件列表的提示信息, 以便更灵活地定制后端接口
        // itemRender(originNode, file, fileList, actions) {
        //     console.log("file", file)
        //     console.log("originNode",originNode)
        //     if (file.status === 'error' && file.response ) {
        //         const originProps = originNode.props;
        //         console.log("originNode.props",originProps)
        //         let cusProps = originProps;
        //         if(originProps.title){
        //              cusProps = React.cloneElement(originProps, { title: "123"})
        //         }
        //       // const cusProps = originProps;//React.cloneElement(originNode.props, { title: "123"})
        //     console.log("cusProps",cusProps)
        //       const cusOrgiginNode = React.cloneElement(originNode, { props: cusProps });
        //
        //     console.log("cusOrgiginNode",cusOrgiginNode)
        //       return cusOrgiginNode;
        //     }
        //     return originNode;
        // }
    };
    const [refreshFlag, setRefreshFlag] = useState(true);
    const sysConfig = useSelector(state => state.pz.sysConfig);
    const [runLoading, setRunLoading] = useState(false);
    const tabItems = [
        {
            key: '1',
            label: '数据统计',
            icon: <Analysis theme="outline"/>,
            children: <DataReport/>
        },
        {
            key: '2',
            label: '上传记录',
            icon: <History theme="outline"/>,
            children: <UploadRecord/>
        }
    ];

    const handleRun = async () => { 
        try {
        setRunLoading(true);
        await request.post('/u8/update');
        message.success('同步成功！');
        setTimeout(() => {
            window.location.reload();
        }, 1000);
        } catch (error) {
        if (error.response) {
            message.error(`同步失败: ${error.response.data.message}`);
        } else {
            console.error('同步数据失败:', error);
            message.error('同步数据失败，请稍后再试。');
        }
        } finally {
        setRunLoading(false);
        }
    };

    return (
        <div style={{minHeight: 'calc(100vh - 112px)'}}>
            <Row justify="center">

                <Col xs={24} sm={20} md={24} hidden={sysConfig.databasetype !== 'GS'}>
                    <div className="config-page-layout float-center" style={backgroundStyle}>
                        <div className="upper-section" >
                            <Title>
                                数据上传
                            </Title>
                            <div className="App">
                                <Dragger {...props}>
                                    <p className="ant-upload-drag-icon">
                                        <InboxOutlined/>
                                    </p>
                                    <p className="ant-upload-text">点击或拖拽文件到此区域以上传文件</p>
                                    <p className="ant-upload-hint">
                                        支持上传Excel文件.xlsx和.xlsm格式; 支持多文件上传
                                    </p>
                                </Dragger>
                            </div>

                        </div>

                        {/* 下部分的表格 */}
                        <div className="lower-section">

                            <Tabs items={tabItems} key={refreshFlag}></Tabs>
                        </div>
                    </div>
                </Col>
                <Col xs={24} sm={20} md={24} hidden={sysConfig.databasetype !== 'U8'}>
                    <div className="config-page-layout float-center" style={backgroundStyle}>
                        <div className="upper-section" >
                            <Title>
                                数据同步
                                {/* 保存和运行按钮 */}
                                <Space className='float-right' style={{ marginBottom: 16, marginLeft: 8 }}>
                                    <Button type="primary" onClick={handleRun} loading={runLoading} className='float-right'>
                                        同步
                                    </Button>
                                </Space>
                            </Title>
                        </div>

                        {/* 下部分的表格 */}
                        <div className="lower-section">
                             <DataReport/>
                        </div>
                    </div>
                </Col>
            </Row>
        </div>

    );
}

export default FileUpload;



